/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.kreig133.analytic.builder;

import com.kreig133.analytic.interfaces.DataMiner;
import com.kreig133.analytic.interfaces.ViewDataHandler;
import com.kreig133.builder.ParametrsForBuild;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import java.util.Map;

/**
 *
 * @author eshangareev
 */
class AnalyticBuilder {

    protected ViewDataHandler current;
    protected ParametrsForBuild parametrsForBuild;

    public AnalyticBuilder() {
    }

    public void setParametrsForBuild(ParametrsForBuild parametrsForBuild) {
        this.parametrsForBuild = parametrsForBuild;
    }

    public void setDataMiner(DataMiner dataMiner) {
        if (current == null) {
            current = dataMiner;
        }
    }

    public void createHandlers() {
        assert current != null;
        assert parametrsForBuild != null;
        try {
            for (Map<String, String> map : parametrsForBuild.getParametrs()) {
                String clazzName = map.remove("class");
                Class clazz = Class.forName(clazzName);
                Constructor constructor = clazz.getConstructor(ViewDataHandler.class);
                current = (ViewDataHandler) constructor.newInstance(current);
                setParametrsToObject(current, map);
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }

    }

    private void setParametrsToObject(Object object, Map<String, String> parametrs) {
        try {
            Method[] methods = object.getClass().getMethods();
            for (String key : parametrs.keySet()) {
                for (Method m : methods) {
                    if (m.getName().toLowerCase().equals("set" + key)) {
                        m.invoke(object,
                                m.getParameterTypes()[0].getConstructor(String.class).newInstance(parametrs.get(key)));
                    }
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
    
    public ViewDataHandler getAnalyticChain(){
        return current;
    }
}
